<template>
  <ProjectInfo
    :preview="true"
    :sign="true"
    :sync="true"
    :projectId="`${route.query.projectId}`"
    :reportType="'LLNOX'"
    @on-sync-header="onSyncHeader"
    @preview-file="previewFile"
    :syncContent="'从采样单中同步信息'"
    ref="projectInfoRef"
    :needSignatureCheck="true"
    @signature="handleSignature"
  />
  <div>
    <div v-if="!sampleHandoverList.length" class="empty-tip"> 点击同步获取数据</div>
    <div v-for="(item, idx) in sampleHandoverList" :key="idx" class="record-item">
      <SampleHandoverRecord title="样品交接记录表" :form-data="item" @update="(val) => onRecordUpdate(val, idx)" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import SampleHandoverRecord from './SampleHandoverRecord.vue'
import { ProjectApi } from '@/api/dk/project'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'

const route = useRoute()
const router = useRouter()
const sampleHandoverList = ref<any[]>([])
defineOptions({ name: 'SampleHandoverIndex' })

const projectInfoRef = ref()
const handleSignature = () => {
  // 先进行数据校验
  if (signatureCheck()) {
    // 校验通过，显示签名弹窗
    if (projectInfoRef.value) {
      projectInfoRef.value.showSignatureDialog()
    }
  }
  // 校验不通过时，不显示弹窗，错误信息已在 signatureCheck 中提示
}

// 签名前整体校验：校验 SampleHandoverRecord 的表格必填项不能为空
const signatureCheck = (): boolean => {
  // 列表为空
  if (!Array.isArray(sampleHandoverList.value) || sampleHandoverList.value.length === 0) {
    ElMessage.warning('暂无数据，请先点击同步获取数据')
    return false
  }

  // 表格内需要校验的字段及其中文名
  const requiredFields: Record<string, string> = {
    inspectionItems: '检测项目',
    sampleNo: '测量编号',
    airCollector: '空气收集器',
    sampleStatus: '样品状态',
    samplingVolume: '采样体积(L)',
    preservationConditions: '样品保存期限和保存条件'
  }

  // 遍历每一天的交接记录
  for (let i = 0; i < sampleHandoverList.value.length; i++) {
    const record: any = sampleHandoverList.value[i] || {}
    const dayLabel = record?.samplingPeriod ? `第${record.samplingPeriod}天` : `第${i + 1}组`
    const table: any[] = Array.isArray(record?.table) ? record.table : []

    if (table.length === 0) {
      ElMessage.error(`${dayLabel}的表格数据不能为空`)
      return false
    }

    for (let r = 0; r < table.length; r++) {
      const row = table[r] || {}
      for (const key of Object.keys(requiredFields)) {
        const label = requiredFields[key]
        const val = row[key]

        // 空字符串、null、undefined 都视为未填；数组需有值
        const isEmpty = Array.isArray(val) ? val.length === 0 : val === '' || val === null || val === undefined
        if (isEmpty) {
          ElMessage.error(`${dayLabel} 第${r + 1}行「${label}」不能为空`)
          return false
        }
      }

      // 采样体积数值性与正数校验（若可转为数字）
      const vol = Number(row.samplingVolume)
      if (Number.isFinite(vol) && vol <= 0) {
        ElMessage.error(`${dayLabel} 第${r + 1}行「采样体积(L)」需为大于0的数值`)
        return false
      }
    }
  }

  return true
}

/** 添加开始调查方法 */
const previewFile = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 10
    }
  })
}

const onSyncHeader = async () => {
  const projectId = route.query.projectId as string
  const result = await ProjectApi.getDefaultSampleHandoverRecord(Number(projectId))
  console.log('同步结果:', JSON.stringify(result))
  sampleHandoverList.value = result || []
  ElMessage.success('从方案同步成功')
  // 新增：同步后手动触发 onRecordUpdate
  updateSampleHandoverRecord()
}

const onRecordUpdate = (val, idx) => {
  sampleHandoverList.value[idx] = val
  console.log('form updated:', JSON.stringify(val))
  updateSampleHandoverRecord()
}

const updateSampleHandoverRecord = () => {
  ProjectApi.updateSampleHandoverRecord({
    projectId: route.query.projectId,
    sampleHandoverList: sampleHandoverList.value
  })
}

onMounted(async () => {
  const projectId = route.query.projectId as string
  const { sampleHandoverList:sampleHandovers } = await ProjectApi.getSampleHandoverRecord(Number(projectId))
  console.log('数据', JSON.stringify(sampleHandovers))
  sampleHandoverList.value = sampleHandovers || []
})
</script>

<style lang="scss" scoped>
.top {
  padding-bottom: 20px;

  .top-btns {
    display: flex;
    justify-content: flex-end;
  }
}

.empty-tip {
  text-align: center;
  color: #bfbfbf;
  margin: 40px 0;
}
</style>
